package cn.exrick.xboot.modules.content.serviceimpl;

import cn.exrick.xboot.base.XbootBaseDao;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentIndexVo;
import cn.exrick.xboot.modules.content.dao.HontUserPostDao;
import cn.exrick.xboot.modules.content.entity.HontUser;
import cn.exrick.xboot.modules.content.entity.HontUserPost;
import cn.exrick.xboot.modules.content.service.HontUserPostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Slf4j
@Service
@Transactional
public class HontUserPostServiceImpl implements HontUserPostService {

    @Autowired
    private HontUserPostDao hontUserPostDao;
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public XbootBaseDao<HontUserPost, String> getRepository() {
        return hontUserPostDao;
    }

    @Override
    public List<HontUserPost> findByHontUserId(String userId) {
        return hontUserPostDao.findByHontUserId(userId);
    }

    @Override
    public void deleteByHontUserId(String userId) {
        hontUserPostDao.deleteByHontUserId(userId);
    }

    public int batchInsert(List<HontUser> users) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO hont_user_post(id,hont_post_id, hont_user_id ) VALUES ");
        for(HontUser userPost : users) {
            sb.append("(REPLACE(UUID(),\"-\",\"\"),?, ?),");
        }
        String sql = sb.toString().substring(0, sb.length() - 1);
        log.info("sql",sql);
        Query query = entityManager.createNativeQuery(sql);
        int paramIndex = 1;
        for(HontUser userPost : users) {
            query.setParameter(paramIndex++, userPost.getPostId());
            query.setParameter(paramIndex++, userPost.getId());
        }
        return query.executeUpdate();
    }
}
